<?php

function _serialize($obj){ 
   return base64_encode(gzcompress(serialize($obj))); 
} 

function _unserialize($txt){
   return unserialize(gzuncompress(base64_decode($txt))); 
}

function is_php($version = '5.0.0'){
		static $_is_php;
		$version = (string)$version;

		if ( ! isset($_is_php[$version]))
		{
			$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
		}

		return $_is_php[$version];
}
	

function new_addslashes($string){

	if(!is_array($string)) return addslashes($string);
	foreach($string as $key => $val) $string[$key] = new_addslashes($val);
	return $string;
}

/*数组转字符串*/
function Array2String($Array){
		if(!$Array)return false;
		$Return='';
		$NullValue="^^^";
		foreach ($Array as $Key => $Value) {
			if(is_array($Value))
				$ReturnValue='^^array^'.Array2String($Value);
			else
				$ReturnValue=(strlen($Value)>0)?$Value:$NullValue;
			$Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';
		}
		return urlencode(substr($Return,0,-2));
}


function String2Array($String){
	if(NULL==$String)return false;
    $Return=array();
    $String=urldecode($String);
    $TempArray=explode('||',$String);
    $NullValue=urlencode(base64_encode("^^^"));
    foreach ($TempArray as $TempValue) {
        list($Key,$Value)=explode('|',$TempValue);
        $DecodedKey=base64_decode(urldecode($Key));
        if($Value!=$NullValue) {
            $ReturnValue=base64_decode(urldecode($Value));
            if(substr($ReturnValue,0,8)=='^^array^')
                $ReturnValue=String2Array(substr($ReturnValue,8));
            $Return[$DecodedKey]=$ReturnValue;
        }
        else
        $Return[$DecodedKey]=NULL;
    }
    return $Return;
}


function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);		
	return $string;
}

function get_LOCAL_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}


function get_now_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$path=explode('/',safe_replace($_SERVER['SCRIPT_NAME']));
	if(count($path)==3){
		return $sys_protocal.$_SERVER['HTTP_HOST'].'/'.$path[1];
	}
	if(count($path)==2){
		return $sys_protocal.$_SERVER['HTTP_HOST'];
	}
}



function _htmtguolv($content) {
		$content = str_replace('%','%&lrm;',$content);
		$content = str_replace("<", "&lt;", $content);
		$content = str_replace(">", "&gt;", $content);            
		$content = str_replace("\n", "<br/>", $content);
		$content = str_replace(" ", "&nbsp;", $content);
		$content = str_replace('"', "&quot;", $content);
		$content = str_replace("'", "&#039;", $content);
		$content = str_replace("$", "&#36;", $content);
		$content = str_replace('}','&rlm;}',$content);
		return $content;
}


function _checkmobile($mobilephone=''){
	if(strlen($mobilephone)!=11){	return false;	}
	if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$mobilephone)){   
		return true;
	}else{   
		return false;
	}
}
	

function _checkemail($youjian=''){
		if(mb_strlen($youjian)<5){
			return false;
		}
		$res="/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/";
		if(preg_match($res,$youjian)){
			return true;
		}else{
			return false;
		}
}	

function _encrypt($string, $operation = 'ENCODE', $key = '', $expiry = 0){
	if($operation == 'DECODE') {
		$string =  str_replace('_', '/', $string);
	}
	$key_length = 4;
	if(defined("YYS_BANBEN_NUMBER")){
			$key = md5($key != '' ? $key : System::DOWN_sys_config("code","code"));
	}else{
			$key = md5($key != '' ? $key : YYS_LOCAL_PATH);
	}
	$fixedkey = md5($key);
	$egiskeys = md5(substr($fixedkey, 16, 16));
	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));

	$i = 0; $result = '';
	$string_length = strlen($string);
	for ($i = 0; $i < $string_length; $i++){
		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
	}
	if($operation == 'ENCODE') {
		$retstrs =  str_replace('=', '', base64_encode($result));
		$retstrs =  str_replace('/', '_', $retstrs);
		return $runtokey.$retstrs;
	} else {	
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	}
}


function _getcookie($name){
	if(empty($name)){return false;}
	if(isset($_COOKIE[$name])){
		return $_COOKIE[$name];
	}else{		
		return false;
	}
}

function _setcookie($name,$value,$time=0,$path='/',$yuming=''){		
	if(empty($name)){return false;}
	$_COOKIE[$name]=$value;				//及时生效
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	if(!$time){
		return setcookie($name,$value,0,$path,$yuming,$s);
	}else{
		return setcookie($name,$value,time()+$time,$path,$yuming,$s);
	}
}



function _strlen($str=''){
	if(empty($str)){
		return 0;
	}
	if(!_is_utf8($str)){
		$str=iconv("GBK","UTF-8",$str);
	}
	return ceil((strlen($str)+mb_strlen($str,'utf-8'))/2);
}
	

 	
function templates($module = '', $moban = '',$StyleTheme=''){	
		if(empty($StyleTheme)){$style=YYS_STYLE.DIRECTORY_SEPARATOR.YYS_STYLE_HTML;}
		else{
			$mobans=System::DOWN_sys_config('templates',$style);
			$style=$mobans['dir'].DIRECTORY_SEPARATOR.$mobans['html'];
		}
		$Filedwt = YYS_CACHES.'caches_template'.DIRECTORY_SEPARATOR.dirname($style).DIRECTORY_SEPARATOR.md5($module.'.'.$moban).'.temp.php';	
		$FileHtml = YYS_TEMPLATES.$style.DIRECTORY_SEPARATOR.$module.'.'.$moban.'.dwt';
		//var_dump($FileHtml);
		//exit;
		if(file_exists($FileHtml)){		
			if (file_exists($Filedwt) && @filemtime($Filedwt) >= @filemtime($FileHtml)) {					
				return $Filedwt;			
			} else {			
				$moban_cache=&System::DOWN_sys_class('template_cache');	
				if(!is_dir(dirname(dirname($Filedwt)))){
					mkdir(dirname(dirname($Filedwt)),0777, true)or die("Not Dir");		
				    chmod(dirname(dirname($Filedwt)),0777);
				}
				if(!is_dir(dirname($Filedwt))){		
					mkdir(dirname($Filedwt), 0777, true)or die("Not Dir");
					chmod(dirname($Filedwt),0777);
				}	
				$PutFiledwt=$moban_cache->template_init($Filedwt,$FileHtml,$module,$moban);
				if($PutFiledwt)
					return $Filedwt;
				else				
					_error('文件不存在');
			}
		}
		_error('文件不存在');
		
	}


function _strcut($string, $changdugth,$dot = '...') {
        $string = trim($string);        
        if($changdugth && strlen($string) > $changdugth) {   
            //截断字符   
            $wordscut = '';   
			if(strtolower(YYS_CHARSET) == 'utf-8') {           
                //utf8编码   
                $n = 0;
                $tn = 0;   
                $noc = 0;   
                while ($n < strlen($string)) {   
                    $t = ord($string[$n]);   
                    if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {   
                        $tn = 1;   
                        $n++;   
                        $noc++;   
                    } elseif(194 <= $t && $t <= 223) {   
                        $tn = 2;   
                        $n += 2;   
                        $noc += 2;   
                    } elseif(224 <= $t && $t < 239) {   
                        $tn = 3;   
                        $n += 3;   
                        $noc += 2;   
                    } elseif(240 <= $t && $t <= 247) {   
                        $tn = 4;   
                        $n += 4;   
                        $noc += 2;   
                    } elseif(248 <= $t && $t <= 251) {   
                        $tn = 5;   
                        $n += 5;   
                        $noc += 2;   
                    } elseif($t == 252 || $t == 253) {   
                        $tn = 6;   
                        $n += 6;   
                        $noc += 2;   
                    } else {   
                        $n++;   
                    }   
                    if ($noc >= $changdugth) {   
                        break;   
                    }   
                }   
                if ($noc > $changdugth) {   
                    $n -= $tn;   
                }   
                $wordscut = substr($string, 0, $n);   
            } else {   
                for($i = 0; $i < $changdugth - 1; $i++) {   
                    if(ord($string[$i]) > 127) {   
                        $wordscut .= $string[$i].$string[$i + 1];   
                        $i++;   
                    } else {   
                        $wordscut .= $string[$i];   
                    }   
                }   
            }   
            $string = $wordscut.$dot;
        }   
        return trim($string);
}


function _huode_ip(){
	if (isset($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], "unknown")) 
		$ip = $_SERVER['HTTP_CLIENT_IP']; 
	else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], "unknown")) 
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
	else if (isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
		$ip = $_SERVER['REMOTE_ADDR']; 
	else if (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
		$ip = $_SERVER['REMOTE_ADDR']; 
	else $ip = ""; 
	return ($ip);
}

function get_real_ip(){
	
	$ip=false;
	if(!empty($_SERVER["HTTP_CLIENT_IP"])){
	$ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
	if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
	for ($i = 0; $i < count($ips); $i++) {
	if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {
	$ip = $ips[$i];
	break;
	}
	}
	}
	$ip = $_SERVER["REMOTE_ADDR"];

	file_put_contents('/log/ipmac3.txt',var_export($ip,true)."\r\n",FILE_APPEND);	
return $ip;
	
}
function get_onlineip() {
    $ch = curl_init('http://www.ip138.com/ip2city.asp');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $a  = curl_exec($ch);
    preg_match('/[(.*)]/', $a, $ip);
    return $ip[1];
 }
function _huode_ip_dizhi($ip=null){
	$opts = array(
		'http'=>array(
		'method'=>"GET",
		'timeout'=>5,)
	);		
	$context = stream_context_create($opts); 
	
	
	if($ip){
		$ipmac = $ip;
	}else{
		//$ipmac = get_real_ip();  //修改后机器人IP不对改回20160921
		$ipmac = _huode_ip();
		if(strpos($ipmac,"127.0.0.") === true)return '';		
	}
	

	$url_ip='http://ip.taobao.com/service/getIpInfo.php?ip='.$ipmac;
	$str = @file_get_contents($url_ip, false, $context);
	if(!$str) return "";
	$json=json_decode($str,true);
	if($json['code']==0){
		
		$json['data']['region'] = addslashes(_htmtguolv($json['data']['region']));
		$json['data']['city'] = addslashes(_htmtguolv($json['data']['city']));
		
		$ipcity= $json['data']['region'].$json['data']['city'];
		$ip= $ipcity.','.$ipmac;
	}else{
		$ip="";
	}
	return $ip;
}



function _is_utf8($string) {
	return preg_match('%^(?:
					[\x09\x0A\x0D\x20-\x7E] # ASCII
					| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
					| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
					| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
					| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
					| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
					| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
					)*$%xs', $string);
}



function _sendemail($youjian,$weername=null,$biaoti='',$content='',$yes='',$no=''){
	System::DOWN_sys_class("email",'sys',"no");
	$config=System::DOWN_sys_config('email');
	if(!$weername)$weername="";
	if(!$yes)$yes="发送成功,如果没有收到，请到垃圾箱查看,\n请把".$config['fromName']."设置为信任,方便以后接收邮件";
	if(!$no)$no="发送失败，请重新点击发送";
	if(!_checkemail($youjian)){return false;}	
	email::config($config);
	if(is_array($youjian)){
		email::adduser($youjian);	
	}else{
		email::adduser($youjian,$weername);
	}	
	$if=email::send($biaoti,$content);
	if($if){
			return $yes;
	}else{
			return $no;
	}
}



function _sendmobile($mobiles='',$content=''){
	$mobiles=str_replace("，",',',$mobiles);
	$mobiles=str_replace(" ",'',$mobiles);
	$mobiles=trim($mobiles," ");
	$mobiles=trim($mobiles,",");
	$sends=System::DOWN_sys_class('sendmobile');
	$config=array();
	$config['mobile']=$mobiles;
	$config['content']= $content;	
	$config['ext']='';
	$config['stime']='';
	$config['rrid']='';
	$cok=$sends->init($config);
	if(!$cok){
		return array('-1','配置不正确!');
	}	
	$sends->send();
	$sendarr=array($sends->error,$sends->v);
	return $sendarr;
}


function get_end_time(){
	
	$EndTime=explode(" ",microtime());
	$StartTime=explode(" ",G_YYS_TIME);
	return intval($EndTime[1]-$StartTime[1])+($EndTime[0]-$StartTime[0]).'/S';
}

function huode_end_memory(){
	$memory=memory_get_usage();
	$memory=$memory/1024;
	return round($memory,2).'/KB';
}


function _note($string=null,$defurl=null,$time=2,$config=null){
	
	if(empty($defurl)){
		$defurl=G_YYS_REFERER;
		if(empty($defurl))$defurl=G_YYS_REFERER;
	}
	if(defined("G_IN_ADMIN")){
		if(empty($config)){
			$config = array("titlebg"=>"#549bd9","title"=>"#fff");
		}		
		$str_url_two=array("url"=>LOCAL_PATH.'/'.G_ADMIN_DIR,"text"=>"返回后台首页");
	}else{
		$str_url_two=array("url"=>YYS_LOCAL_PATH,"text"=>"返回首页");
	}
	$time=intval($time);if($time<2){$time=2;}
	include templates("system","message");
	exit;
}



function _notemobile($string=null,$defurl=null,$time=2,$config=null){
	if(empty($defurl)){
		$defurl=G_YYS_REFERER;
		if(empty($defurl))$defurl=LOCAL_PATH;
	}
	if(empty($config)){
		if(DOWN_M==System::DOWN_sys_config("system","admindir")){		
			$config=array();
			$config['titlebg']='#549bd9';$config['title']='#fff';
		}
	}
	$time=intval($time);if($time<2){$time=2;}
	include templates("mobile/system","message");
	exit;
}



function _error($biaoti,$content){
	if(empty($biaoti)){$biaoti='文件不存在哦';}
	if(empty($content)){$content='文件不存在哦';}
	echo 'error!!';
	exit;
}


function _is_ie() {
	$weeragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if((strpos($weeragent, 'opera') !== false) || (strpos($weeragent, 'konqueror') !== false)) return false;
	if(strpos($weeragent, 'msie ') !== false) return true;
	return false;
}

function _is_mobile() { 
    $weer_agent = $_SERVER['HTTP_USER_AGENT']; 
    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte"); 
    $is_mobile = false; 
    foreach ($mobile_agents as $device) { 
        if (stristr($weer_agent, $device)) { 
            $is_mobile = true; 
            break; 
        } 
    } 
    return $is_mobile; 
}

	

function _error_handler(){
	error_reporting(E_ERROR | E_WARNING | E_PARSE);
	ini_set("display_errors","OFF");					 				
	ini_set("error_log",YYS_CACHES."error.".date("Y-m-d").".logs");	   

}


function _huodecode($n=10){
	$num=intval($n) ? intval($n) : 10;
	if($num>44)
		$codestr=base64_encode(md5(time()).md5(time()));
	else
		$codestr=base64_encode(md5(time()));
	$temp=array();
	$temp['code']=substr($codestr,0,$num);
	$temp['time']=time();
	return $temp;
}



function _yys($name=''){
	return System::DOWN_sys_config('system',$name);
}





function _g_YYSabcde($url,$io=false,$post_data = array(), $cookie = array()){
		$method = empty($post_data) ? 'GET' : 'POST';
		
        $url_array = parse_url($url);		
        $port = isset($url_array['port'])? $url_array['port'] : 80; 
		
		if(function_exists('fsockopen')){
			$fp = @fsockopen($url_array['host'], $port, $errno, $errstr, 30);
		}elseif(function_exists('pfsockopen')){
			$fp = @pfsockopen($url_array['host'], $port, $errno, $errstr, 30);
		}elseif(function_exists('stream_socket_client')){
			$fp = @stream_socket_client($url_array['host'].':'.$port,$errno,$errstr,30);
		} else {
			$fp = false;
		}
		
        if(!$fp){
             return false;
        }		
		
		
		
		$url_array['query'] =  isset($url_array['query']) ? $url_array['query'] : '';		
        $getPath = $url_array['path'] ."?". $url_array['query'];
		
        $header  = $method . " " . $getPath." ";
        $header .= "HTTP/1.1\r\n";
        $header .= "Host: ".$url_array['host']."\r\n"; //HTTP 1.1 Host域不能省略
		$header .= "Pragma: no-cache\r\n";
		
        
      
	
        if(!empty($cookie)){
                $_cookie_s = strval(NULL);
                foreach($cookie as $k => $v){
                        $_cookie_s .= $k."=".$v."; ";
                }
				$_cookie_s = rtrim($_cookie_s,"; ");
                $cookie_str =  "Cookie: " . base64_encode($_cookie_s) ." \r\n";	   //传递Cookie
                $header .= $cookie_str;
        }
		$post_str = '';
         if(!empty($post_data)){
                $_post = strval(NULL);
                foreach($post_data as $k => $v){
                        $_post .= $k."=".urlencode($v)."&";
                }
				$_post = rtrim($_post,"&");
                $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
                $header .= "Content-Length: ". strlen($_post) ." \r\n";//POST数据的长度	
				
                $post_str = $_post."\r\n"; //传递POST数据
        }
		$header .= "Connection: Close\r\n\r\n";
		$header .= $post_str;
		
        fwrite($fp,$header);
		if($io){		
			 while (!feof($fp)){ 
                   echo fgets($fp,1024);
			 }
		}   
        fclose($fp);
		//echo $header;
        return true;
}




function _buy_time($time = 0,$test=''){
	if(empty($time)){return $test;}
	$time = substr($time,0,10);
	$ttime = time() - $time;
	if($ttime <= 0 || $ttime < 60){
		return '几秒前';
	}	
	if($ttime > 60 && $ttime <120){
		return '1分钟前';
	}
	
	$i = floor($ttime / 60);							//分
	$h = floor($ttime / 60 / 60);						//时
	$d = floor($ttime / 86400);							//天
	$m = floor($ttime / 2592000);						//月
	$y = floor($ttime / 60 / 60 / 24 / 365);			//年
	if($i < 30){
		return $i.'分钟前';
	}
	if($i > 30 && $i < 60){
		return '一小时内';
	}
	if($h>=1 && $h < 24){
		return $h.'小时前';
	}
	if($d>=1 && $d < 30){
		return $d.'天前';
	}	
	if($m>=1 && $m < 12){		
		return $m.'个月前';
	}
	if($y){
		return $y.'年前';
	}	
	return "";
	
}



function huode_lanmu($cid){
	if(empty($cid)){
		return '';
	}
	$db = System::DOWN_sys_class("model");
	$info = $db->YOne("SELECT name FROM `@#_fenlei` where `cateid` = '$cid' limit 1");
	if($info){
		return $info['name'];
	}else{
		return '';
	}

}


function _session_start(){
	if(!isset($_SESSION)){ session_start();}
}


function _session_destroy(){
	if(isset($_SESSION)){session_destroy();}
}



function _xml_to_array($xml){
	$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
	if(preg_match_all($reg, $xml, $matches)){
	$count = count($matches[0]);
		for($i = 0; $i < $count; $i++){
			$subxml= $matches[2][$i];
			$key = $matches[1][$i];
				if(preg_match( $reg, $subxml )){
					$arr[$key] = _xml_to_array( $subxml );
				}else{
					$arr[$key] = $subxml;
				}
			}
		}
	return $arr;
}

function push_weixin_msg_autolottery($shopid,$goodname,$qishu,$code,$uid1){
	/*$db = System::DOWN_sys_class("model");
	$uid_list = $db->Ylist("SELECT r.uid,r.huode,y.openid,y.username FROM `@#_yonghu_yys_record` r LEFT JOIN  `@#_yonghu` y ON r.uid= y.uid WHERE r.shopid=$shopid  GROUP BY r.uid ");
	$zjz = $db->YOne("SELECT username FROM  `@#_yonghu` WHERE uid = ".$uid1);
	foreach ($uid_list as $k => $v) {
		push_weixin_msg(2,$v['openid'],$v['username'].'|'.$zjz['username'],$v['uid'],$goodname,$qishu,$code);
	}*/
	return true;
}


/*微信消息推送*/
function push_wx_msg_new($type,$openid,$pushData){

	if(!$openid){
		return true;
	}
	$db = System::DOWN_sys_class("model");
	$msg_tpl = "select * from wp_wx_reply_list where tplType = '$type' and status = '1'";
	$msg_tpl = $db->YOne($msg_tpl);
	if(!$msg_tpl || !$msg_tpl['tpl'] || $msg_tpl['status'] == '0'){
		return true;
	}

	$msg = $msg_tpl['tpl'];
	
	//序列化参数
	foreach($pushData as $key => $one){
		$msg = str_replace(wx_msg_type_array($key),$one, $msg);
	}
	
	$access_token = file_get_contents('http://weiphp.gou12345.com/index.php?s=/home/index/ajax_access_token');
	$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
	//$url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token='. $access_token;
	$data['touser'] = $openid;
	$data['msgtype'] = 'text';
	$data['text']['content'] = urlencode(htmlspecialchars_decode($msg));
	$data = urldecode(json_encode($data));
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, "content-type: application/json; charset=UTF-8");
	curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
	curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	$res = curl_exec ( $ch );
	$flat = curl_errno ( $ch );
	curl_close ( $ch );
	$return_array && $res = json_decode ( $res, true );
	return true;
}


function wx_msg_type_array($key){
	$array = array(
		'username' => '[会员名]',
		'gzs' => '[关注数]',
		'invite' => '[邀请人]',
		'qishu' => '[期数]',
		'shopname' => '[商品名]',
		'webname'	=> '[网站名称]',
		'pricename' => '[会员名1]',
		'huode' => '[惠券码]',
		'jibie' => '[级别]',
		'bzjje' => '[保证金数额]',
		'status' => '[状态]',
		'money' => '[金额]',
		'fenhong' => '[分红]',
		'envelopeType' => '[红包类型]',
		'days' => '[返还天数]',
		'expressName' => '[快递名称]',
		'expressCode' => '[物流单号]',
	);
	return $array[$key];
}


function push_weixin_msg($type,$openid,$username,$uid,$goodname,$qishu,$other){
	/*if(!$openid){
		return true;
	}
	$db = System::DOWN_sys_class("model");
	$msg_temp = $db->YOne("SELECT * FROM wp_public WHERE id = 1 ");
	if($type==1){
		$msg = $msg_temp['buy_remarks'];
		$msg = str_replace('[会员名]',$username, $msg);
		$msg = str_replace('[期数]',$qishu, $msg);
		$msg = str_replace('[商品名]',$goodname, $msg);
	}elseif ($type==2) {
		$msg = $msg_temp['autolottery_remarks'];
		$username = explode('|', $username);
		$msg = str_replace('[会员名]',$username[0], $msg);
		$msg = str_replace('[会员名1]',$username[1], $msg);
		$msg = str_replace('[期数]',$qishu, $msg);
		$msg = str_replace('[商品名]',$goodname, $msg);
		$msg = str_replace('[惠券码]',$other, $msg);
	}elseif ($type==3) {
		$msg = $msg_temp['lottery_remarks'];
		$msg = str_replace('[会员名]',$username, $msg);
		$msg = str_replace('[期数]',$qishu, $msg);
		$msg = str_replace('[商品名]',$goodname, $msg);
	}
	$access_token = file_get_contents('http://weiphp.gou12345.com/index.php?s=/home/index/ajax_access_token');
	$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
	$data['touser'] = $openid;
	$data['msgtype'] = 'text';
	$data['text']['content'] = urlencode(htmlspecialchars_decode($msg));
	$data = urldecode(json_encode($data));
	file_put_contents('1.txt', $data);
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, "content-type: application/json; charset=UTF-8");
	curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
	curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	$res = curl_exec ( $ch );
	$flat = curl_errno ( $ch );
	curl_close ( $ch );
	$return_array && $res = json_decode ( $res, true );*/
	return true;
}

function wechat_login(){
	$db = System::DOWN_sys_class("model");
	$uid = intval(_encrypt(_getcookie('uid'),'DECODE'));

	$sql="select * FROM `@#_yonghu` WHERE `uid` = '".$uid."' ORDER BY uid asc";
	$userInfo=$db->YOne($sql);
	if(!$userInfo){
		$uid = '';
	}
	//print_r($_COOKIE);
	if(stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')!==false ){

		if(!$uid){
			$weixin_config_rows = $db->YOne(' SELECT appid , secret FROM wp_public WHERE id = 1');
		    $weixin_config_rows['appsecret'] = $weixin_config_rows['secret'];
		    if($_GET['code']){
		        $back_openid_arr= json_decode(httpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$weixin_config_rows['appid']."&secret=".$weixin_config_rows['appsecret']."&code=".$_GET['code']."&grant_type=authorization_code"),true);
		        _setcookie('openid',$back_openid_arr['openid']);
		        _setcookie('A_token',$back_openid_arr['access_token'],time()+1296000);
		        $pattern1 = '/[\?]code=[^&]*/i';
		        $pattern2 = "/&code=[^&]*/";
		        $uri=preg_replace($pattern1, '', $_SERVER['REQUEST_URI']);
		        $uri=preg_replace($pattern2, '', $uri);
				$uri=str_replace('&state=','',$uri);
		        $url="http://" . $_SERVER['HTTP_HOST'] .$uri;
		        header("location:".$url."");
		    }
			
			

		    if( !_getcookie('openid')|| !_getcookie('A_token') ){
		        $redirect_uri = urlencode('http://m.gou12345.com'.$_SERVER['REQUEST_URI'] );

		        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$weixin_config_rows['appid']."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo#wechat_redirect";
		        header("location:".$url."");
		        exit;
		    }
			

		    if(_getcookie('openid')){
		        if(_getcookie('A_token')){
		            $userinfo = json_decode(httpGet("https://api.weixin.qq.com/sns/userinfo?access_token="._getcookie('A_token')."&openid="._getcookie('openid')),true);
		            $userinfo['nickname'] = json_decode(preg_replace("/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]{1,20}$/u",'',json_encode($userinfo['nickname']) ));
		        }

		        $sql="select * FROM `@#_yonghu` WHERE openid ='"._getcookie('openid')."' ORDER BY uid asc";
		        $huiyuan=$db->YOne($sql);

		        if($huiyuan){
					session_start(); 
					$session_id=session_id();
					$ip = _huode_ip_dizhi();
					$time = time();

					//$touxiang = saveimage($userinfo['headimgurl']);
					$db->Query("UPDATE `@#_yonghu` SET session_id='$session_id',`user_ip`='$ip',`login_time`='$time' where uid='$huiyuan[uid]'");
					_setcookie("uid",_encrypt($huiyuan['uid']),60*60*24*7);
					_setcookie("uidss",_encrypt($huiyuan['uid']),60*60*24*7);			
					_setcookie("ushell",_encrypt(md5($huiyuan['uid'].$huiyuan['password'].$huiyuan['mobile'].$huiyuan['email'])),60*60*24*7);
					//print_r($_COOKIE);
					if($userinfo['nickname']!=$huiyuan['username'] && $userinfo['nickname']){
						$db->Query("UPDATE `@#_yonghu` SET username='{$userinfo['nickname']}' where uid='$huiyuan[uid]'");
					}
					$regtype = System::DOWN_app_config("user_reg_type",'','member');
					if($regtype['reg_bind']){
						if($huiyuan['mobilecode']==-1 && !strstr($_SERVER['REQUEST_URI'] ,'mobilebind') && !strstr($_SERVER['REQUEST_URI'] ,'accountbind') ){
							header('Location:/mobile/home/mobilebind/');
						}
					}
		        }else{
					header('Location:/mobile/mobile/guanzhu/');
		        	exit();
		        }
		    }
	    }else{

	        if(_getcookie('openid')){
	        	$access_token = httpGet('http://weiphp.gou12345.com/index.php?s=/home/index/ajax_access_token');
	            $userinfo = json_decode(httpGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid="._getcookie('openid')."&lang=zh_CN"),true);
	            $userinfo['nickname'] = json_decode(preg_replace("/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]{1,20}$/u",'',json_encode($userinfo['nickname']) ));
	        }
			$sql="select * FROM `@#_yonghu` WHERE `uid` = '".$uid."' or openid ='"._getcookie('openid')."' ORDER BY uid asc";
	        $huiyuan=$db->YOne($sql);

	        if($huiyuan){
				session_start(); 
				$session_id=session_id();
				$ip = _huode_ip_dizhi();
				$time = time();
				//$touxiang = saveimage($userinfo['headimgurl']);
				
				$db->Query("UPDATE `@#_yonghu` SET `session_id`='$session_id',`user_ip`='$ip',`login_time`='$time' where uid='$huiyuan[uid]'");
				_setcookie("uid",_encrypt($huiyuan['uid']),60*60*24*7);		
				_setcookie("uidss",_encrypt($huiyuan['uid']),60*60*24*7);	
				_setcookie("ushell",_encrypt(md5($huiyuan['uid'].$huiyuan['password'].$huiyuan['mobile'].$huiyuan['email'])),60*60*24*7);
				if($userinfo['nickname']!=$huiyuan['username'] && $userinfo['nickname']){
					$db->Query("UPDATE `@#_yonghu` SET username='{$userinfo['nickname']}' where uid='$huiyuan[uid]'");
				}
				
				$regtype = System::DOWN_app_config("user_reg_type",'','member');
				if($regtype['reg_bind']){
					if($huiyuan['mobilecode']==-1 && !strstr($_SERVER['REQUEST_URI'] ,'mobilebind') && !strstr($_SERVER['REQUEST_URI'] ,'accountbind') ){
						header('Location:/mobile/home/mobilebind/');
					}
				}
	        }
	    }
	}

}
	//下载头像
	function saveimage($url)
	{
		if(function_exists('curl_init')){
			$curl = curl_init($url);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_FAILONERROR, true);
			curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			$content =  curl_exec($curl);
			curl_close($curl);
		}else{
			$content = @file_get_contents($url);
		}
		$dir="touimg/".date("Ymd").'/';
		$date_dir = G_UPLOAD.'/'.$dir;
		//echo $date_dir;exit;
		
		(!is_dir($date_dir))&&@mkdir($date_dir,0777,true);
		$file_name = uniqid().'';
		$file_path = $date_dir.$file_name.'.jpg';
		if(!empty($content) && @file_put_contents($file_path,$content) > 0)
		{
			System::load_sys_class('upload','sys','no');
			upload::thumbs(160,160,false,$file_path);
			upload::thumbs(80,80,false,$file_path);
			upload::thumbs(30,50,false,$file_path);	
			return $dir.$file_name.'.jpg';
		}
		return 'photo/member.jpg';
	}
function httpGet($url) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_URL, $url);
	$res = curl_exec($curl);
	curl_close($curl);
	return $res;
}
	  
	  
	  
	  
function runReturnList($uid){
	$db = System::DOWN_sys_class("model");
	if($uid){
		$openid = $db->YOne("select * from `@#_yonghu` where `uid` = '$uid'");
		$returnList = $db->YList("select * from `@#_zg_return_list` where `uid` = '$uid' and `status` = '0'");
		if($returnList && $openid['risk'] != 'high'){
			foreach($returnList as $key => $one){
				//先更新返还记录，当前时间大于返还时间
				$time = time();
				if($time > $one['addTime']){
					$updateSql = "UPDATE `@#_zg_return_list` SET `updateTime` = '$time',`status` = '1' WHERE `id` = '$one[id]'";
					$res = $db->Query($updateSql);
					if($res){
						//写入会员账户日志
						$noteSql = "INSERT INTO `@#_yonghu_zhanghao1` (`uid`,`type`,`pay`,`content`,`money`,`time`) VALUES ('$uid','1','金币','直购每日返还','$one[dayMoney]','$time')";
						$res = $db->Query($noteSql);
						if($res){
							$userUpdateSql = "UPDATE `@#_yonghu` SET `money1` = `money1` + '$one[dayMoney]' WHERE `uid` = '$uid'";
							$db->Query($userUpdateSql);
							
							//推送消息
							$type = 'fxrz';
							$pushData = array(
								'username' => $openid['username'],
								'webname' => _yys("web_name"),
								'shopname' => $one['shopname'],
								'money' => $one['dayMoney']
							);
							push_wx_msg_new($type,$openid['openid'],$pushData);
						}
					}
				}
			}
		}
	}
}


function autoShelve(){
	$db = System::DOWN_sys_class("model");
	$list = $db->YList("select * from `@#_sqfb` where `isShevel` = '1'");
	foreach($list as $key => $one){
		$supplier = $db->YOne("select * from `@#_yonghu` where `uid` = '$one[uid]'");
		if(($supplier['supplyGradeTime'] + 3600*24*365) < time()){
			$sql = "UPDATE `@#_sqfb` SET `isShevel` = '0' WHERE `id` = '$one[id]'";
			$db->Query($sql);
		}
	}
}

function math_width($a,$b){
	return ($a/$b)*100;
}


/*新增部分2017-04-05 孙阳*/
function httpPost($url){
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL, $url); 
	curl_setopt($ch, CURLOPT_VERBOSE, true); 
	curl_setopt($ch, CURLOPT_HEADER,0);
	curl_setopt($ch, CURLOPT_NOBODY,1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,0); 
	curl_setopt($ch, CURLOPT_TIMEOUT, 20); 
	curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
	$ret = curl_exec($ch); 
	$info = curl_getinfo($ch); 
	return $info;
}

/*Json输出*/
function ajaxReturn($status,$msg,$url=null){
	echo json_encode(array(
		'status' => $status,
		'msg' => $msg,
		'url' => $url
	));
}

/*DB函数*/
function insertInto($array,$table){
	$db = System::DOWN_sys_class("model");
	$keyStr = '(';
	foreach($array as $key => $one){
		$keyStr .= "`$key`,";
	}
	$keyStr = substr($keyStr,0,strlen($keyStr)-1).')';
	
	$valueStr = '(';
	foreach($array as $key => $one){
		$valueStr .= "'".htmlspecialchars($one)."',";
	}
	$valueStr = mb_substr($valueStr,0,mb_strlen($valueStr)-1).')';
	$sql = "INSERT INTO `@#_$table` $keyStr VALUES $valueStr";
	$db->tijiao_start();
	$returnId = $db->query($sql);
	$returnId = $db->last_id();
	if($returnId){
		$db->tijiao_commit();
	}else{
		$db->tijiao_rollback();
	}
	return $returnId;
}

/*UPDATE 更新*/
function updateSet($array,$table,$id,$type=1){
	$sql = "UPDATE `@#_$table` SET ";
	foreach($array as $key => $one){
		$sql .= "`$key` = '$one',";
	}
	$sql  = mb_substr($sql,0,mb_substr($sql)-1);
	if($type == 1){
		$sql .= " WHERE `id` = '$id'";
	}else{
		$sql .= " WHERE `$type` = '$id'";
	}

	$db = System::DOWN_sys_class("model");
	return $db->query($sql);
}

/*DB函数部分完*/

/*URL参数转数组*/
function convertUrlQuery($query){
	$queryParts = explode('&', $query);
	$params = array();
	foreach ($queryParts as $param) {
		$item = explode('=', $param);
		$params[$item[0]] = urldecode($item[1]);
	}
	return $params;
}

/*身份证检查*/
function isCreditNo($vStr){
	$vCity = array(
		'11','12','13','14','15','21','22',
		'23','31','32','33','34','35','36',
		'37','41','42','43','44','45','46',
		'50','51','52','53','54','61','62',
		'63','64','65','71','81','82','91'
	);
	if(!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
	if(!in_array(substr($vStr, 0, 2), $vCity)) return false;
	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	$vLength = strlen($vStr);
	if($vLength == 18){
		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	}else{
		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	}
	if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
	if ($vLength == 18) {
		$vSum = 0;
		for ($i = 17 ; $i >= 0 ; $i--) {
			$vSubStr = substr($vStr, 17 - $i, 1);
			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
		}
		if($vSum % 11 != 1) return false;
	}
	return true;
}

/*获取省市名*/
function getCityName($code){
	$db = System::DOWN_sys_class("model");
	$name = $db->YOne("select name from `@#_area` where `code` = '$code'");
	if($name){
		return $name['name'];
	}else{
		return '';
	}
}

function getSupplierAddress($supplier_id,$deep=1){
	$db = System::DOWN_sys_class("model");
	$supplier = $db->YOne("select * from `@#_supplier` where id = '$supplier_id'");
	if($deep == 1){
		return getCityName($supplier['province']);
	}elseif($deep == 2){
		return getCityName($supplier['province']).getCityName($supplier['city']);
	}elseif($deep == 3){
		return getCityName($supplier['province']).getCityName($supplier['city']).getCityName($supplier['country']);
	}else{
		return getCityName($supplier['province']).getCityName($supplier['city']).getCityName($supplier['country']).getCityName($supplier['street']);
	}
}

/*获取行业服务名*/
function getSupplierType($id){
	$db = System::DOWN_sys_class("model");
	$name = $db->YOne("select * from `@#_fenlei` where `cateid` = '$id'");
	$uname = $db->YOne("select * from `@#_fenlei` where `cateid` = '$name[parentid]'");
	if($name){
		return $uname['name'].'-'.$name['name'];
	}else{
		return '';
	}
}

/*获取商户信息*/
function getSupplierInfo($id,$type=null){
	$db = System::DOWN_sys_class("model");
	if(!$type){
		$type = '*';
	}else{
		$utype = $type;
		$type = " `$type` ";
	}
	$supplier = $db->YOne("select $type from `@#_supplier` where id = '$id'");
	if($supplier){
		if($type != '*'){
			return $supplier[$utype];
		}else{
			return $supplier;
		}
	}else{
		return '暂无此商户';
	}
}

/*获取卡券分类信息*/
function getCouponCate($id){
	$db = System::DOWN_sys_class("model");
	$couponCate = $db->YOne("select `name` from `@#_supplier_coupon_cate` where id = '$id'");
	if($couponCate){
		return $couponCate['name'];
	}else{
		return '暂无此卡券分类';
	}
}

/*获取卡券信息*/
function getSupplierCouponStatus($id){
	$db = System::DOWN_sys_class("model");
	$couponStatus = $db->YOne("select `status` from `@#_supplier_coupon` where id = '$id'");
	if($couponStatus){
		if($couponStatus['status'] == 0){
			return '<span style="color:blue;">待审核</span>';
		}elseif($couponStatus['status'] == 1){
			return '<span style="color:green;">已审核</span>';
		}elseif($couponStatus['status'] == 2){
			return '<span style="color:red;">已拒绝</span>';
		}
	}else{
		return '暂无此卡券';
	}
}

/*截取字符串*/
function getSubstr($str,$len=20){
	$str = mb_substr($str,0,$len);
	return $str.'...';
}

/*调试函数*/
function a($data){
	echo "<pre>";
	print_r($data);
	die();
}

/*获取会员详情*/
function getUserInfo($uid,$type='uid',$word='*'){
	$db = System::DOWN_sys_class("model");
	if($type == 'uid'){
		$userInfo = $db->Yone("select $word from `@#_yonghu` where `uid` = '$uid'");
	}else{
		$userInfo = $db->Yone("select $word from `@#_yonghu` where `$type` = '$uid'");
	}
	if($word != '*'){
		return $userInfo[$word];
	}
	return $userInfo;
}

/*删除某条记录*/
function deleteInfo($id,$table,$type='id'){
	$db = System::DOWN_sys_class("model");
	$res = $db->query("delete from `@#_$table` where `$type` = '$id'");
	if($res){
		return true;
	}else{
		return false;
	}
}

/*手机验证*/
function checkMobile($mobile){
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

/*查询该会员是否获奖过*/
function isWin($uid){
	$q_uid = $db->YOne("select * from `@#_shangpin` where `q_uid` = '$uid'");
	if($q_uid){
		return true;
	}else{
		return false;
	}
}

/*时间转换*/
function formatTime($date,$format='Y-m-d H:i:s'){
	return date($format,$date);
}

/*获取码*/
function getUserCode($id,$type=null){
	$db = System::DOWN_sys_class("model");
	$shopInfo = $db->Yone("select * from `@#_shangpin` where `id` = '$id'");
	$q_user_code = $shopInfo['q_user_code'];
	$code = $db->YOne("select * from `@#_yonghu_yys_record` where `huode` = '$q_user_code' and `shopid` = '$id' and `uid` = '$shopInfo[q_uid]'");
	if($code){
		if($type){
			return $code[$type];
		}else{
			$goucode = explode(',',$code['goucode']);
			return count($goucode);
		}
	}else{
		return '没有购买';
	}
}

/*格式化取分类*/
function getCategoryFromat($cateid,$info=null,$type=null){
	$db = System::DOWN_sys_class("model");
	if($info){
		if($type){
			$info = unserialize($info);
			if($type == 'thumb' && $info[$type]){
				return $info[$type];
			}else{
				return _yys('web_logo');
			}
		}else{
			return unserialize($info);
		}
	}else{
		
	}
}

function getCateGoods($supplierId,$isShelve){
	$db = System::DOWN_sys_class("model");
	$cate = $db->YList("select * from `@#_fenlei` where `parentid` != '0' and `model` = '1' and `type` = '1' order by `order` desc");
	$cateArray = array();
	foreach($cate as $key => $one){
		$shangpin = $db->YList("select * from `@#_zg_shangpin` where `catesubid` = '$one[cateid]' and `supplierId` = '$supplierId' and `isShelve` = '$isShelve' order by `sort` desc");
		if(count($shangpin) > 0){
			$cateArray[] = $one;
		}
	}
	return $cateArray;
}

function getSupplierPatComment($pid){
	$db = System::DOWN_sys_class("model");
	$comment_count = $db->YOne("select count(*) as `count` from `@#_supplier_pat_comment` where `pid` = '$pid'");
	return $comment_count['count'] ? $comment_count['count'] : 0;
}

function getExpressOrderSn($express_id){
	$db = System::DOWN_sys_class("model");
	$express = $db->YOne("select * from `@#_express_list` where `id` = '$express_id'");
	return $express ? $express['express_sn'] : '暂无物流信息';
}

function cutstr_html($string,$length=0,$ellipsis='…'){
	$string=strip_tags($string);
	$string=preg_replace('/\n/is','',$string);
	$string=preg_replace('/ |　/is','',$string);
	$string=preg_replace('/&nbsp;/is','',$string);
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/",$string,$string);
	if(is_array($string)&&!empty($string[0])){
		if(is_numeric($length)&&$length){
			$string=join('',array_slice($string[0],0,$length)).$ellipsis;
		}else{
			$string=implode('',$string[0]);
		}
	}else{
		$string='';
	}
	return $string;
}